<?php

namespace App\Repositories;

use App\Models\TestingSendTplUser;
use Cache;
class TestingSendTplUserRepository extends Repository
{
    static $tag = 'testing.SendTplUser';

    /**存储用户
     * @param $data
     * @return static
     */
    public function storeUser($data)
    {
        $res = $this->checkUser($data['uid'],$data['appid'],$data['tid']);
        if($res){//存在删除之前记录
            TestingSendTplUser::where('uid', $data['uid'])
                ->where('tid',$data['tid'])
                ->where('appid',$data['appid'])
                ->delete();
        }
        return TestingSendTplUser::create($data);
    }

    /**结束发送模板消息更新数据
     * @param $data
     * @return mixed
     */
    public function updateStatus($data){
        return TestingSendTplUser::where('uid', $data['uid'])
            ->where('tid',$data['tid'])
            ->where('appid',$data['appid'])
            ->update(['is_start' => $data['is_start'],'end_time'=>$data['end_time']]);
    }

    /**查找用户是否存在
     * @param $uid
     * @param $appid
     * @param $tid
     * @return mixed
     */
    public function checkUser($uid,$appid,$tid){
        return TestingSendTplUser::where('uid', $uid)
            ->where('tid',$tid)
            ->where('appid',$appid)
            ->orderBy('id', 'desc')
            ->first();
    }

    /**根据tid,appid获取正在进行模板消息推送的用户组
     * @param $appid
     * @param $tid
     */
    public function getByAppid($appid,$tid){
       $res =  TestingSendTplUser::select('uid')
            ->where('appid', $appid)
            ->where('tid', $tid)
            ->where('is_start',1)
            ->get()->toarray();
        if($res){
          return  array_column($res,'uid');
        }else{
            return false;
        }
    }



    public function cacheTime()
    {
        return config('testing.common_cache_time');
    }


    public function model()
    {
        return app(TestingSendTplUser::class);
    }

    public function tag()
    {
        return self::$tag;
    }
}